package com.leapp.sk.view.im

import android.Manifest
import android.app.Activity
import android.content.Context
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.*
import cc.vv.lkbasecomponent.util.LKScreenUtil
import cc.vv.lkimcomponent.view.emoji.EmojiParser
import cc.vv.lkimcomponent.view.emoji.ParseEmojiOperate
import cc.vv.lklibrary.log.LogOperate
import com.example.baselibrary.util.SKPermissionUtils
import com.example.util.closeInput
import com.leapp.sk.R
import com.leapp.sk.bean.EmojiconEntity
import com.leapp.sk.bean.EmojiconGroupEntity
import com.leapp.sk.util.im.BigEmojiconDatas
import com.leapp.sk.util.im.EaseDefaultEmojiconDatas
import com.leapp.sk.util.im.EmojiconUtils
import java.io.File

/**
 * 输入框布局封装
 * @author  chaohaipeng  on 2018/7/12.
 */
class SKChatInputMenu : SKChatInputMenuBase, View.OnClickListener{

    /**
     * 上下文
     */
    var mContext: Activity? = null
    /**
     * 按住讲话按钮管理父布局
     */
    var ll_swcm_bottom: LinearLayout? = null
    /**
     * 语音按钮
     */
    var btn_swcm_set_mode_voice: Button? = null

    /**
     * 键盘输入标识按钮
     */
    var btn_swcm_set_mode_keyboard: Button? = null

    /**
     * 按住说话布局
     */
    var ll_swcm_press_to_speak: LinearLayout? = null
    /**
     * 按住说话文字
     */
    var tv_swcm_press_to_speak: TextView? = null


    /**
     * 键盘输入父布局
     */
    var rl_swcm_input_layout: RelativeLayout? = null
    /**
     * 内容输入
     */
    var et_swcm_sendmessage: EditText? = null
    /**
     * 表情管理父布局
     */
    var rl_swcm_face: RelativeLayout? = null
    /**
     * 普通状况下的表情
     */
    var iv_swcm_face_normal: ImageView? = null
    /**
     * 选中后
     */
    var iv_swcm_face_checked: ImageView? = null
    /**
     * 表情布局
     */
    var fm_swcm_emojicon_menu_container: FrameLayout? = null
    /**
     * 更多内容布局
     */
    var fm_swcm_menu_container: FrameLayout? = null
    /**
     * 更多内容按钮
     */
    var btn_swcm_more: Button? = null
    /**
     * 发送按钮
     */
    var btn_swcm_send: Button? = null
    /**
     * 发送按钮
     */
    var v_swcm_view: View? = null

    /**
     * 照片
     */
    var rl_lscc_camera: RelativeLayout? = null
    /**
     *视频
     */
    var rl_lscc_video: RelativeLayout? = null

    /**
     * 控制是否被按下
     */
    private var ctrlPress = false
    var emojiconMenu: SKEmojiconMenu? = null
    /**
     * 输入菜单监听  如果在当前View中回调listener其他地方用该监听
     */
    var mchatInputMenuListener:ChatInputMenuListener?=null

    /**
     * 语音控件Y坐标
     */
    private var voiceViewY: Float =0f
    /**
     * 当前和语音坐标距离
     */
    private var abs: Float =0f
    /**
     * 是否处于长按
     */

    private var isVoiceLongClick = false
    constructor(context: Context) : super(context) {
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    }
    /**
     * 初始化布局
     */
    fun init(activity: Activity) {
        mContext = activity
        val view = LayoutInflater.from(mContext).inflate(R.layout.sk_widget_chat_menu, this)
        ll_swcm_bottom = view.findViewById(R.id.ll_swcm_bottom)
        fm_swcm_emojicon_menu_container = view.findViewById(R.id.fm_swcm_emojicon_menu_container)
        fm_swcm_menu_container = view.findViewById(R.id.fm_swcm_menu_container)
        btn_swcm_set_mode_voice = view.findViewById(R.id.btn_swcm_set_mode_voice)
        v_swcm_view = view.findViewById(R.id.v_swcm_view)
        rl_lscc_camera = view.findViewById(R.id.rl_lscc_camera)
        rl_lscc_video = view.findViewById(R.id.rl_lscc_video)
        btn_swcm_set_mode_keyboard = view.findViewById(R.id.btn_swcm_set_mode_keyboard)
        ll_swcm_press_to_speak = view.findViewById(R.id.ll_swcm_press_to_speak)
        tv_swcm_press_to_speak = view.findViewById(R.id.tv_swcm_press_to_speak)
        rl_swcm_input_layout = view.findViewById(R.id.rl_swcm_input_layout)
        et_swcm_sendmessage = view.findViewById(R.id.et_swcm_sendmessage)
        rl_swcm_face = view.findViewById(R.id.rl_swcm_face)
        iv_swcm_face_normal = view.findViewById(R.id.iv_swcm_face_normal)
        iv_swcm_face_checked = view.findViewById(R.id.iv_swcm_face_checked)
        btn_swcm_more = view.findViewById(R.id.btn_swcm_more)
        btn_swcm_send = view.findViewById(R.id.btn_swcm_send)
        addemojicn()
        emojiconMenu?.addEmojiconGroup(BigEmojiconDatas.getData())
        initEvent()
    }




    /**
     * 添加表情
     */
    fun addemojicn() {
        var emojiconGroupList = arrayListOf<EmojiconGroupEntity>()
        if (emojiconMenu == null) {
            emojiconMenu = LayoutInflater.from(mContext).inflate(R.layout.sk_emojicon_menu, null) as SKEmojiconMenu?
            if (emojiconGroupList.size == 0) {
                emojiconGroupList.add(EmojiconGroupEntity(
                        R.mipmap.ease_chatting_biaoqing_btn_enable, EaseDefaultEmojiconDatas.getData())
                )
            }
            emojiconMenu?.init(emojiconGroupList)
        }
        fm_swcm_emojicon_menu_container?.addView(emojiconMenu)
        processChatMenu()
    }

    /**
     * 判断菜单是否打开
     */
     fun meunIsOpen():Boolean{
         if (fm_swcm_emojicon_menu_container?.visibility== View.VISIBLE||fm_swcm_menu_container?.visibility== View.VISIBLE){
             fm_swcm_emojicon_menu_container?.visibility= View.GONE
             fm_swcm_menu_container?.visibility= View.GONE
             return true
         }
         return false
     }
    /**
     * 输入框监听
     */
    protected fun processChatMenu() {
        setChatInputMenuListener(object : SKChatInputMenuListener {
            override fun onSendBtnClicked(content: String) {
                mchatInputMenuListener?.onSendMessage(content)
            }

            override fun onToggleVoiceBtnClicked() {
                hideExtendMenuContainer()
            }

            override fun onToggleExtendClicked() {
                toggleMore()
            }

            override fun onToggleEmojiconClicked() {
                toggleEmojicon()
            }

            override fun onEditTextClicked() {
                hideExtendMenuContainer()
            }

            override fun onPressToSpeakBtnTouch(v: View, event: MotionEvent): Boolean {
              val isPermission=  SKPermissionUtils.getInstance().requestAudio(mContext)
                if (!isPermission){
                    return true
                }
                when (event.action) {
                    MotionEvent.ACTION_DOWN->{
                        abs = 0f
                        voiceViewY = ll_swcm_press_to_speak!!.getY()
                        ll_swcm_press_to_speak?.setOnLongClickListener(OnLongClickListener {
                            LKVoiceRecorderView.getInstance().showVoiceView(tv_swcm_press_to_speak, mContext,mchatInputMenuListener)
                            isVoiceLongClick = true
                            false
                        })
                    }
                    MotionEvent.ACTION_MOVE -> if (isVoiceLongClick) {
                        val y = event.y
                        abs = Math.abs(Math.abs(y) - voiceViewY)
                        if (abs > LKScreenUtil.dp2px(50f)) {
                            LKVoiceRecorderView.getInstance().cancelRecording(tv_swcm_press_to_speak)
                        } else {
                            LKVoiceRecorderView.getInstance().recording(tv_swcm_press_to_speak)
                        }
                    }
                    MotionEvent.ACTION_UP -> {
                        if (isVoiceLongClick) {
                            if (abs >LKScreenUtil.dp2px(50f)) {
                                LKVoiceRecorderView.getInstance().cancelSend(tv_swcm_press_to_speak)
                            } else {
                                if (abs >= 0) {
                                    tv_swcm_press_to_speak?.text=mContext?.resources?.getString(R.string.string_im_long_normal)
                                    LKVoiceRecorderView.getInstance().stopRecord()
                                }
                            }
                        }
                    }
                    MotionEvent.ACTION_CANCEL -> if (isVoiceLongClick) {
                        LKVoiceRecorderView.getInstance().cancelSend(tv_swcm_press_to_speak)
                    }
                }
                return false
            }

        })
    }

    fun setChatInputMenuListener(chatInputMenuListener:ChatInputMenuListener){
        mchatInputMenuListener=chatInputMenuListener
    }

    /**
     * 隐藏或展示菜单
     *
     */
    protected fun toggleMore() {
        if (fm_swcm_menu_container?.visibility == View.GONE) {
            closeInput(mContext, mContext?.window?.decorView)
            handler.postDelayed({
                fm_swcm_menu_container?.visibility = View.VISIBLE
                fm_swcm_emojicon_menu_container?.visibility = View.GONE
            }, 200)
        } else {
            fm_swcm_menu_container?.visibility = View.GONE
            if (emojiconMenu?.visibility === View.VISIBLE) {
            } else {
                fm_swcm_menu_container?.visibility = View.GONE
            }
        }
    }

    /**
     * 隐藏菜单
     */
    fun hideExtendMenuContainer() {
        fm_swcm_emojicon_menu_container?.visibility = View.GONE
        emojiconMenu?.visibility = View.GONE
        onExtendMenuContainerHide()
    }

    /**
     * 隐藏或展示表情
     */
    protected fun toggleEmojicon() {
        if (fm_swcm_emojicon_menu_container?.visibility == View.GONE) {
            showSelectedFaceImage()
            closeInput(mContext, mContext?.window?.decorView)
            handler.postDelayed({
                fm_swcm_emojicon_menu_container?.visibility = View.VISIBLE
                fm_swcm_menu_container?.visibility = View.GONE
                emojiconMenu?.visibility = View.VISIBLE
            }, 200)
        } else {
            if (emojiconMenu?.visibility == View.VISIBLE) {
                fm_swcm_emojicon_menu_container?.visibility = View.GONE
                showNormalFaceImage()
                emojiconMenu?.visibility = View.GONE
            } else {
                emojiconMenu?.visibility = View.VISIBLE
            }

        }
    }


    /**
     * 初始化监听事件
     */
    fun initEvent() {
        rl_lscc_camera?.setOnClickListener(this)
        rl_lscc_video?.setOnClickListener(this)
        btn_swcm_send?.setOnClickListener(this)
        btn_swcm_set_mode_keyboard?.setOnClickListener(this)
        btn_swcm_set_mode_voice?.setOnClickListener(this)
        btn_swcm_more?.setOnClickListener(this)
        rl_swcm_face?.setOnClickListener(this)
        et_swcm_sendmessage?.setOnClickListener(this)
        et_swcm_sendmessage?.requestFocus()
        et_swcm_sendmessage?.onFocusChangeListener = object : OnFocusChangeListener {
            override fun onFocusChange(p0: View?, hasFocus: Boolean) {
                if (hasFocus) {
                    v_swcm_view?.setBackgroundColor(ContextCompat.getColor(mContext,R.color.color_19AD19))
                } else {
                    v_swcm_view?.setBackgroundColor(ContextCompat.getColor(mContext,R.color.color_CCCCCC))
                }
            }

        }
        et_swcm_sendmessage?.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (!TextUtils.isEmpty(s)) {
                    btn_swcm_more?.visibility = View.GONE
                    btn_swcm_send?.visibility = View.VISIBLE
                } else {
                    btn_swcm_more?.visibility = View.VISIBLE
                    btn_swcm_send?.visibility = View.GONE
                }
            }

            override fun afterTextChanged(p0: Editable?) {
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

        })
        et_swcm_sendmessage?.setOnKeyListener(object : OnKeyListener {
            override fun onKey(p0: View?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
                    if (event?.action == KeyEvent.ACTION_DOWN) {
                        ctrlPress = true
                    } else if (event?.action == KeyEvent.ACTION_UP) {
                        ctrlPress = false
                    }
                }
                return false

            }

        })
        et_swcm_sendmessage?.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(p0: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEND || event?.keyCode == KeyEvent.KEYCODE_ENTER &&
                        event?.action == KeyEvent.ACTION_DOWN &&
                        ctrlPress) {
                    val s = et_swcm_sendmessage?.text.toString().trim()
                    et_swcm_sendmessage?.setText("")
                    listener?.onSendBtnClicked(s)
                    return true
                } else {
                    return false
                }
            }
        })
        ll_swcm_press_to_speak?.setOnTouchListener { view, motionEvent ->
                listener?.onPressToSpeakBtnTouch(view, motionEvent)
            false
        }

        emojiconMenu?.setEmojiconMenuListener(object :SKEmojiconMenuBase.SKEmojiconMenuListener{
            override fun onDeleteImageClicked() {
                if (!TextUtils.isEmpty(et_swcm_sendmessage?.text)) {
                    val event = KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL)
                    et_swcm_sendmessage?.dispatchKeyEvent(event)
                }
            }
            override fun onExpressionClicked(emojicon: EmojiconEntity) {
                LogOperate.e("表情===" + emojicon.type)
                if (emojicon.type!=EmojiconEntity.Type.BIG_EXPRESSION) {
                    if (!TextUtils.isEmpty(emojicon.emojiText)) {
                        val spannableString = ParseEmojiOperate.getInstance().parseEmoji(emojicon.emojiText, 20)
//                        val smiledText = EmojiconUtils.getSmiledText(context, emojicon.emojiText)
                        et_swcm_sendmessage?.append(spannableString)
                    }
                } else {
                    LogOperate.e("大表情===" + emojicon.emojiText)
                    mchatInputMenuListener?.onBigExpressionClicked(emojicon)
                }
            }
        })

    }

    /**
     *语音模式
     *
     */
    fun setModeVoice() {
        rl_swcm_input_layout?.visibility = View.GONE
        btn_swcm_set_mode_voice?.visibility = View.GONE
        btn_swcm_set_mode_keyboard?.visibility = View.VISIBLE
        btn_swcm_send?.visibility = View.GONE
        btn_swcm_more?.visibility = View.VISIBLE
        ll_swcm_press_to_speak?.visibility = View.VISIBLE
        iv_swcm_face_normal?.visibility = View.VISIBLE
        iv_swcm_face_checked?.visibility = View.INVISIBLE

    }

    /**
     * 键盘模式
     */
    fun setModeKeyboard() {
        rl_swcm_input_layout?.visibility = View.VISIBLE
        btn_swcm_set_mode_keyboard?.visibility = View.GONE
        btn_swcm_set_mode_voice?.visibility = View.VISIBLE
        et_swcm_sendmessage?.requestFocus()
        ll_swcm_press_to_speak?.visibility = View.GONE
        if (TextUtils.isEmpty(et_swcm_sendmessage?.text)) {
            btn_swcm_more?.visibility = View.VISIBLE
            btn_swcm_send?.visibility = View.GONE
        } else {
            btn_swcm_more?.visibility = View.GONE
            btn_swcm_send?.visibility = View.VISIBLE
        }

    }

    /**
     * 更多模式
     */
    fun setMoreMode() {
        btn_swcm_set_mode_voice?.visibility = View.VISIBLE
        btn_swcm_set_mode_keyboard?.visibility = View.GONE
        rl_swcm_input_layout?.visibility = View.VISIBLE
        ll_swcm_press_to_speak?.visibility = View.GONE
    }

    override fun onExtendMenuContainerHide() {
        fm_swcm_menu_container?.visibility = View.GONE
    }
    /**
     * 表情切换
     */
    fun toggleFaceImage() {
        if (iv_swcm_face_normal?.visibility == View.VISIBLE) {
            showSelectedFaceImage()
        } else {
            showNormalFaceImage()
        }
    }
    /**
     * 默认下表情
     */
    fun showNormalFaceImage() {
        iv_swcm_face_normal?.visibility = View.VISIBLE
        iv_swcm_face_checked?.visibility = View.INVISIBLE
    }

    /**
     * 选中下表情
     */
    fun showSelectedFaceImage() {
        iv_swcm_face_normal?.visibility = View.INVISIBLE
        iv_swcm_face_checked?.visibility = View.VISIBLE
    }

    override fun onTextInsert(text: CharSequence) {
        val start = et_swcm_sendmessage?.selectionStart
        val editable = et_swcm_sendmessage?.editableText
        if (start != null) {
            editable?.insert(start, text)
        }
        setModeKeyboard()
    }
    override fun getEditText(): EditText? {
        return et_swcm_sendmessage
    }
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btn_swcm_send -> send()
            R.id.btn_swcm_set_mode_voice -> {
                setModeVoice()
                showNormalFaceImage()
                listener?.onToggleVoiceBtnClicked()
            }
            R.id.btn_swcm_set_mode_keyboard -> {
                setModeKeyboard()
                showNormalFaceImage()
                listener?.onToggleVoiceBtnClicked()
            }
            R.id.btn_swcm_more -> {
                setMoreMode()
                showNormalFaceImage()
                listener?.onToggleExtendClicked()
            }
            R.id.et_swcm_sendmessage -> {
                v_swcm_view?.setBackgroundColor(ContextCompat.getColor(mContext,R.color.color_19AD19))
                fm_swcm_emojicon_menu_container?.visibility=View.GONE
                iv_swcm_face_normal?.visibility = View.VISIBLE
                iv_swcm_face_checked?.visibility = View.INVISIBLE
                listener?.onEditTextClicked()
            }
            R.id.rl_swcm_face -> {
                toggleFaceImage()
                listener?.onToggleEmojiconClicked()
            }
          R.id.rl_lscc_camera->{
              mchatInputMenuListener?.onImageExpressionClicked()
          }
            R.id.rl_lscc_video->{
                mchatInputMenuListener?.onVideoExpressionClicked()
            }
        }
    }
    fun send() {
        if (listener != null) {
            val s = et_swcm_sendmessage?.text.toString()
            et_swcm_sendmessage?.setText("")
            listener?.onSendBtnClicked(s)
        }
    }
    interface ChatInputMenuListener {
        /**
         * 发送消息按钮
         *
         * @param content
         * message content
         */
        fun onSendMessage(content: String)

        /**
         * 大图被按下时
         * @param emojicon
         */
        fun onBigExpressionClicked(emojicon: EmojiconEntity)

        /**
         * 图片选择
         * @param emojicon
         */
        fun onImageExpressionClicked()
        /**
         * 视频拍摄选择
         * @param emojicon
         */
        fun onVideoExpressionClicked()
        /**
         * 讲话时
         * @param v
         * @param event
         * @return
         */
        fun onSendVoice(voiceDuration:Int,  voicePath:String,  voiceFileName:String,voiceFile: File)

    }

}